<template>
  <div class="row">
    <select-picker-modal ref="selectPickerModal" @value="getPicker" :type="2"></select-picker-modal>
    <!--新： 订单信息+客户信息-->
    <OrderInfo :chOrderService="chOrderService" :chOrderConsigneeInfo="chOrderConsigneeInfo" :state="state"></OrderInfo>
    <Portlet title="商品信息" style="position:relative;">
      <!--<div slot="tools" v-if="distributionStart == false || distributionStart == 'false'">-->
      <div slot="tools">
        <el-button type="primary" @click.prevent="showSelectPickerModal">指派拣货员</el-button>
        <el-button type="primary" :loading="loading" @click.prevent="submit">提交分配</el-button>
        <!--<el-button type="primary" v-if="state == 2" :loading="loading" @click.prevent="submit">打印</el-button>-->
      </div>
      <el-row>
        <!--<el-col :span="24">-->
          <!--<el-form ref="searchForm" class="el-form-col" inline :model="search" label-position="left">-->
            <!--<el-row>-->
              <!--<el-col :lg="5" :xl="5">-->
                <!--<el-form-item prop="manufacturersName" label="厂家名称">-->
                  <!--<el-input clearable placeholder="" v-model="search.manufacturersName"></el-input>-->
                <!--</el-form-item>-->
              <!--</el-col>-->
              <!--<el-col :lg="5" :xl="5">-->
                <!--<el-form-item prop="productName" label="所属产品">-->
                  <!--<el-input clearable placeholder="" v-model="search.productName"></el-input>-->
                <!--</el-form-item>-->
              <!--</el-col>-->
              <!--<el-col :lg="5" :xl="5">-->
                <!--<el-form-item prop="packageName" label="包件名称">-->
                  <!--<el-input clearable placeholder="" v-model="search.packageName"></el-input>-->
                <!--</el-form-item>-->
              <!--</el-col>-->
              <!--<el-col :lg="5" :xl="5">-->
                <!--<el-form-item >-->
                  <!--<el-button type="primary" @click.prevent="reset">重置</el-button>-->
                <!--</el-form-item>-->
              <!--</el-col>-->
            <!--</el-row>-->
          <!--</el-form>-->
        <!--</el-col>-->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="100px">
            <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
             ]">
              <!--新：商品信息-->
              <el-table
                ref="table"
                :data="model.productDetailBeans | filterActive(this.search)"
                style="width:100%"
                border
                class="text-center"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="150px"
                  prop="manufacturersName"
                  label="厂家名称"
                >
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="120px"
                  prop="productNo"
                  label="商品编号">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="120px"
                  prop="productName"
                  label="商品名称">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="120px"
                  prop="bigClass"
                  label="商品大类">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="120px"
                  prop="middleClass"
                  label="商品小类">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="120px"
                  prop="productNum"
                  label="商品数量">
                </el-table-column>
                <el-table-column
                  v-if="productType == 1"
                  align="center"
                  min-width="80px"
                  prop="standard"
                  label="规格">
                </el-table-column>
                <el-table-column
                  v-if="productType == 1"
                  align="center"
                  min-width="120px"
                  prop="packageCode"
                  label="包件编号">
                </el-table-column>
                <el-table-column
                  v-if="productType == 1"
                  min-width="150px"
                  prop="packageName"
                  align="center"
                  label="包件名称">
                </el-table-column>
                <el-table-column
                  align="center"
                  min-width="100px"
                  prop="num"
                  label="包件数量">
                  <!--<template slot-scope="scope">-->
                  <!--{{ scope.row.totalVolume = scope.row.volume * scope.row.num | decimalNumFilter}}-->
                  <!--</template>-->
                </el-table-column>
                <el-table-column
                  v-if="productType == 1"
                  align="center"
                  min-width="100px"
                  prop="packageVolume"
                  label="单包件体积">
                  <template slot-scope="scope">
                    {{ scope.row.packageOneVolume | decimalNumFilter}}
                  </template>
                  <!--<template slot-scope="scope">-->
                  <!--{{ scope.row.totalVolume = scope.row.volume * scope.row.num | decimalNumFilter}}-->
                  <!--</template>-->
                </el-table-column>
                <el-table-column
                  v-if="productType == 1"
                  align="center"
                  min-width="100px"
                  prop="weight"
                  label="单包件重量">
                  <template slot-scope="scope">
                    {{ scope.row.packageOneWeight | decimalNumFilter}}
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="productType == 1 && chOrderService.outTypeCode === 'CARGOSOURCETYPE01'"
                  label="可用库存"
                  prop="canUsePackageNum"
                >
                </el-table-column>
                <el-table-column
                  v-if="productType == 1 && chOrderService.outTypeCode === 'CARGOSOURCETYPE01'"
                  label="库位库存"
                  prop="num"
                >
                </el-table-column>
                <!--当未确认3 + 长期仓储+ 标准产品1：分配库位-->
                <el-table-column
                  v-if="state == 1 && productType == 1 && chOrderService.outTypeCode === 'CARGOSOURCETYPE01'"
                  min-width="200px"
                  align="center"
                  prop="positionId"
                  label="分配库位">
                  <!--旧：-->
                  <!--<template slot-scope="scope">-->
                    <!--<div v-if="distributionStart == false || distributionStart == 'false'">-->
                      <!--<el-form-item label-width="0" :prop="'productDetailBeans.' + scope.$index + '.positionId'" :rules="[-->
                        <!--{required: true, message: '库位必须', trigger: 'change'}-->
                      <!--]">-->
                        <!--<select-position @change="setCanUsePackageNum(scope.row)" :id="chOrderService.orderId" v-model="scope.row.positionId"></select-position>-->
                      <!--</el-form-item>-->
                    <!--</div>-->
                    <!--<div v-else>-->
                      <!--{{ scope.row.positionName }}-->
                    <!--</div>-->
                  <!--</template>-->
                  <!--新：-->
                  <template slot-scope="scope">
                    <el-form-item label-width="0" :prop="'productDetailBeans.' + scope.$index + '.positionId'" :rules="[
                          {required: true, message: '库位必须', trigger: 'change'}
                       ]">
                      <!--<select-position v-model="scope.row.positionId" :id="scope.row.orderId"></select-position>-->
                      <select-position @change="setCanUsePackageNum(scope.row)" :id="chOrderService.orderId" v-model="scope.row.positionId"></select-position>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  v-else
                  align="center"
                  min-width="120px"
                  prop="positionName"
                  label="分配库位">
                </el-table-column>
                <el-table-column
                  prop="packageSortingName"
                  label="拣货员">
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div style="position:absolute;left:140px;top:17px;font-size:14px;color:red">商品类型： {{getProductName(chOrderService.productType)}}</div>
      <!--总的包件体积重量-->
      <el-row style="margin-top:15px;font-size:14px">
        <el-col :span="6">
          总包件：<span> {{chOrderService.totalPackage}} 件</span>
        </el-col>
        <el-col :span="6">
          总体积：<span> {{chOrderService.totalVolume}} m³</span>
        </el-col>
        <el-col :span="6">
          总重量：<span> {{chOrderService.totalWeight}} kg</span>
        </el-col>
      </el-row>
    </Portlet>
  </div>
</template>
<script>
import {dotData, alert} from '@/utils'
import OrderInfo from '@/views/oms/outputWarehouse/warehouseAllocation/OrderInfo'
import SelectPosition from '@/views/oms/business/SelectPositionByEnter'
import SelectPickerModal from '@/views/oms/business/SelectPickerModal'
import {decimalNumFilter, unixTimestampFilter} from '@/filters'
import DBLike from '@/utils/DBLike'

export default {
  name: 'outputWarehouseAllocationShow',
  components: {
    OrderInfo,
    SelectPickerModal,
    SelectPosition
  },
  filters: {
    decimalNumFilter,
    unixTimestampFilter,
    filterActive: (arr, search) => {
      return new DBLike(arr).search(search)
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      distributionStart: this.$route.query.distributionStart,
      state: this.$route.query.state,
      loading: false,
      search: {
        manufacturersName: '',
        productName: '',
        packageName: ''
      },
      params: {
        id: this.$route.params.id
      },
      packageIdArr: [],
      picker: {},
      chOrderService: {},
      chOrderConsigneeInfo: {},
      isVisible: false,
      model: {
        productDetailBeans: [],
        warehouseId: '',
        cargoOwnerId: ''
      },
      warehouseIdArr: [],
      rules: {},
      lastDBArr: []
    }
  },
  created() {
    if (this.id) {
      this.getDetail()
      this.getDatasTable()
    }
  },
  computed: {
    productType() {
      return dotData(this.chOrderService, 'productType')
    },
    // 总包件：总体积：总重量
    totalPackage() {
      let num = 0
      if (Array.isArray(this.model.productDetailBeans)) {
        this.model.productDetailBeans.forEach(v => {
          num += v.planNum
        })
      }
      return decimalNumFilter(num)
    },
    totalVolumes() {
      let num = 0
      if (Array.isArray(this.model.productDetailBeans)) {
        this.model.productDetailBeans.forEach(v => {
          num += v.packageOneVolume * v.num
        })
      }
      return decimalNumFilter(num)
    },
    totalWeight() {
      let num = 0
      if (Array.isArray(this.model.productDetailBeans)) {
        this.model.productDetailBeans.forEach(v => {
          num += v.packageOneWeight * v.num
        })
      }
      return decimalNumFilter(num)
    }
  },
  methods: {
    // 默认全选
    checked() {
      for (let i = 0; i < this.model.productDetailBeans.length; i++) {
        this.$refs.table.toggleRowSelection(this.model.productDetailBeans[i], true)
      }
    },
    // 过滤出 商品类型
    getProductName(type) {
      if (type === 1) {
        return '标准产品'
      } else if (type === 2) {
        return '通用产品'
      } else if (type === 3) {
        return '自定义产品'
      }
      return ''
    },
    setCanUsePackageNum(row) {
      if (row && row.id && row.positionId) {
        return this.$ajax.get('/ms-warehouse-order/storage-location/storage-location-available-stock', {
          locationId: row.positionId,
          outPackageId: row.id
        }).then(response => {
          const success = dotData(response, 'success')
          if (success) {
            this.$set(row, 'canUsePackageNum', dotData(response, 'data'))
          }
        })
      }
    },
    searchFunc() {
      console.log('searchFunc')
    },
    // 重置搜索框
    // reset(searchForm) {
    //   this.$refs.searchForm.resetFields()
    // },
    // 获取详情
    getDetail() {
      this.$ajax.get('/ms-warehouse-order/outWarehose/findByOrderInfo', {outOrderId: this.id}).then(response => {
        if (!response.data) {
          return
        }
        this.chOrderService = dotData(response, 'data') || {}
        this.chOrderConsigneeInfo = dotData(this.chOrderService, 'chOrderConsigneeInfo') || {}
      })
    },
    // 获取包件列表
    getDatasTable() {
      this.$ajax.get('/ms-warehouse-order/outWarehose/findByOutWarehouseInfo', {outOrderId: this.id}).then(response => {
        this.model.productDetailBeans = response.data
        setTimeout(_ => {
          this.checked()
          this.getPickup()
        }, 500)
      })
    },
    // 列表选择
    handleSelectionChange(val) {
      this.packageIdArr = []
      val.forEach(v => {
        this.packageIdArr.push(v.packageId)
      })
    },
    // 显示指派拣货员modal
    showSelectPickerModal() {
      if (this.packageIdArr.length) {
        this.isVisible = true
        this.$refs.selectPickerModal.show()
      } else {
        alert('请选择需要指派的包件！')
      }
    },
    // 获取拣货人
    getPickup() {
      this.$ajax.get('/ms-warehouse-order/inPutWarehouse/getSorterList').then(response => {
        if (!response.data) {
          alert('获取拣货员失败！')
          return
        }
        this.packageIdArr.forEach(v => {
          this.model.productDetailBeans.find((x) => {
            if (x.packageId === v) {
              x.packageSortingId = response.data[0].id
              x.packageSortingName = response.data[0].name
            }
          })
        })
      })
    },
    // 获取拣货员
    getPicker(val) {
      this.picker = val
      if (!this.packageIdArr.length) {
        alert('未获取需指派的包件！')
        return
      }
      if (!this.picker) {
        alert('未获取拣货员')
        return
      }
      this.savePackagePicker()
    },
    // 保存包件拣货员
    savePackagePicker() {
      this.packageIdArr.forEach(v => {
        let that = this
        this.model.productDetailBeans.find((x) => {
          if (x.packageId === v) {
            x.packageSortingId = that.picker.id
            x.packageSortingName = that.picker.name
          }
        })
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          this.$alert('请确认入库单中每个包件均分配了库位及拣货员，需完善后再次提交！', '信息未完善', {
            confirmButtonText: '确定',
            center: true
          })
          return
        }
        // 取值
        let data = {
          id: this.id
        }
        this.loading = true
        let productDetailBeans = []
        if (Array.isArray(this.model.productDetailBeans)) {
          let arr = this.model.productDetailBeans
          for (let i in arr) {
            if (arr[i].id && arr[i].packageSortingId && arr[i].positionId) {
              productDetailBeans.push({
                packageId: arr[i].id,
                positionId: arr[i].positionId,
                sortingPersonId: arr[i].packageSortingId
              })
            } else {
              this.$alert('请确认出库单中每个包件均分配了库位及拣货员，需完善后再次提交！', '信息未完善', {
                confirmButtonText: '确定',
                center: true
              })
              this.loading = false
              return false
            }
          }
        }
        data.chSortingPackageBeans = productDetailBeans
        // 提交
        this.$confirm('<p>确定提交出库计划？</p><p>（提交后将按计划生成拣货单）</p>', '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          center: true,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '提交中...'
              this.$ajax.post('/ms-warehouse-order/outbound-distribution/update-outbound-distribution-list', productDetailBeans).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  this.loading = false
                  setTimeout(() => {
                    this.$confirm('提交成功', '提示', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/ss-oms/outputWarehouse/warehouse-allocation/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.loading = false
                  }, 500)
                }
              })
            } else {
              done()
              this.loading = false
            }
          }
        })
      })
    }
  }
}
</script>
